import { Component, OnInit } from '@angular/core';
import { NzModalService, NzNotificationService } from 'ng-zorro-antd';
import { DataService } from '@shared/service';
import {
  FormControl,
  FormBuilder,
  FormGroup,
  ValidationErrors,
  Validators
} from '@angular/forms';

import { Observable, Observer } from 'rxjs';
@Component({
  selector: 'app-auth',
  templateUrl: './auth.component.html',
  styleUrls: ['./auth.component.less'],
})


export class AuthComponent implements OnInit {
  isDisabled = true;
  x = 1;
  i = 1;
  j = 1;
  validateForm: FormGroup;
  configForm: FormGroup;
  isVisible = false;
  isAddVisible = false;
  inputValue: string;
  displayData: string[] = [];
  childdata: any[] = [];
  editCache: any[] = [];
  editConfig: any[] = [];
  configId: string[] = [];
  configName: string[] = [];
  configRemark: string[] = [];
  optionalFields: string[] = [];
  listOfOption: string[] = [];
  listOfSelectedValue: string[] = [];
  dataSet: any[] = [];
  typeData: any[] = [];
  store: any[] = [];
  params = {};
  allData: any[] = [];
  searchAddress: any[] = [];
  searchValue: any = '';
  sortName: string = null;
  sortValue: string = null;
  isLoadingOne = false;
  isLoadingTwo = false;
  cacheTypeData: any[] = [];
  listOfTagOptions: any[] = [];
  configNameData: any[] = [];
  storeConfigData: any[] = [];
  // 改变搜索框
  onChange(value: any): void {
    this.configNameData = value;
  }
  constructor(private modalService: NzModalService,
    private dataService: DataService, private fb: FormBuilder,
    private notification: NzNotificationService) {
  }
  // 配置页面模态框  打开
  showModal(data): void {
    console.log(data);
    this.configId = data.id;
    this.configName = data.name;
    this.configRemark = data.describe;
    this.childdata = [];
    data.actions.forEach((item, index) => {
      this.x++;
      this.childdata = [...this.childdata, {
        key: `${this.x}`,
        action: item.action,
        describe: item.describe,
        defaultCheck: item.defaultCheck,
      }];
      this.updateEditCacheconfig();
    });
    const optionaData = [];
    this.listOfSelectedValue = [];
    data.optionalFields.forEach((item, index) => {
      optionaData.push({
        label: item.name,
        value: item.name
      });
      this.listOfSelectedValue.push(item.name);
    });
    this.optionalFields = optionaData;
    console.log(this.optionalFields);
    this.isVisible = true;
  }
  handleCancelconfig(): void {
    this.isVisible = false;
  }
  // 获得修改名称的值
  changeName(authName): void {
    this.configNameData = authName;
  }
  // 配置页面 保存
  confighandleOk(): void {
    console.log(this.configForm);
    this.isLoadingTwo = true;  // 加载状态
    this.storeConfigData = null;
    console.log(this.configName);
    this.isVisible = false;
    const store = [];
    // 处理actions 数据
    this.childdata.forEach((item) => {
      store.push({
        action: item.action,
        describe: item.describe,
        defaultCheck: item.defaultCheck,
      });
    });
    // 处理optionalFields数据
    const newOption = [];
    this.listOfSelectedValue.forEach((item) => {
      newOption.push({
        name: item
      });
    });
    const params = {
      id: this.configId,
      name: this.configForm.controls.configName.value,
      actions: store,
      optionalFields: newOption,
      describe: this.configForm.controls.configRemark.value,
    };
    console.log(params);
    // 修改的数据提交到后台
    this.dataService.updateAuth(this.configId, params).subscribe(res => {
      if (res && res.status === 200) {
        this.isLoadingTwo = false;  // 加载状态
        this.getAllData();
        this.createNotification('success', '权限管理', '修改成功！');
      } else {
        this.createNotification('error', '权限管理', '修改失败！');
      }
    }, (error) => {
      this.createNotification('error', '权限管理', '服务器boom!!!');
    });
  }
  // 新增行
  addRowConfig(): void {
    this.x++;
    this.childdata = [...this.childdata, {
      key: `${this.x}`,
      action: ``,
      describe: '',
      defaultCheck: 'true'
    }];
    this.updateEditCacheconfig();
  }
  // 删除行
  deleteRowConfig(j: string): void {
    const childdata = this.childdata.filter(d => d.key !== j);
    this.childdata = childdata;
  }
  // 编辑行
  startEditconfig(key: string): void {
    this.editConfig[key].edit = true;
    console.log(this.childdata);
  }
  // 离开
  cancelEditconfig(key: string): void {
    this.editConfig[key].edit = false;
  }
  saveEditconfig(key: string): void {
    const index = this.childdata.findIndex(item => item.key === key);
    Object.assign(this.childdata[index], this.editConfig[key].data);
    // this.childdata[ index ] = this.editConfig[ key ].data;
    this.editConfig[key].edit = false;
  }
  // 更新修改值
  updateEditCacheconfig(): void {
    this.childdata.forEach(item => {
      if (!this.editConfig[item.key]) {
        this.editConfig[item.key] = {
          edit: false,
          data: { ...item }
        };
      }
    });
    console.log(this.childdata);
  }

  // ****************************************** 新增 ************************************************
  // 新增页面模态框   打开
  showAddModal(data): void {
    console.log(this.validateForm);
    this.listOfTagOptions = [];
    this.cacheTypeData = [];
    this.listOfOption = [];
    this.validateForm.reset();
    this.isAddVisible = true;
    this.dataSet = [];
  }
  // 新增页面模态框  取消
  handleCancelAdd(): void {
    this.isAddVisible = false;
  }
  // 新增页面模态框  保存
  addhandleOk(): void {
    console.log(this.validateForm);
    // 获取类型的值
    const newData = this.listOfTagOptions;
    this.typeData.push({
      name: newData[newData.length - 1]
    });
    console.log(this.typeData);
    this.isLoadingOne = true; // 加载状态
    this.isVisible = false;
    this.dataSet.forEach((item, index) => {
      this.store.push({
        action: item.action,
        describe: item.describe,
        defaultCheck: item.defaultCheck,
      });
    });
    this.params = {
      actions: this.store,
      id: this.validateForm.controls.authID.value,
      name: this.validateForm.controls.authName.value,
      describe: this.validateForm.controls.authRemark.value,
      status: 1,
      parents: [],
      supportDataAccessTypes: [],
      type: 'default',
      optionalFields: this.typeData
    };
    console.log(this.params);
    this.dataService.addAuth(this.params).subscribe(res => {
      // console.log(res);
      if (res && res.status === 200) {
        this.isLoadingOne = false;  // 加载状态
        this.isAddVisible = false; // 模态框消失
        this.getAllData();
        this.createNotification('success', '权限管理', '新增成功！');
      } else {
        this.createNotification('error', '权限管理', '新增失败！');
      }

    }, (error) => {
      this.createNotification('error', '权限管理', '服务器boom!!!');
    });
  }
  createNotification(type: string, title: string, content: string): void {
    this.notification.create(type, title, content);
  }


  // 删除提示框
  showDeleteConfirm(id, name): void {
    this.modalService.confirm({
      nzTitle: '确定要删除吗?',
      nzContent: '<b style="color: red;">' + name + '</b>',
      nzOkText: '删除',
      nzOkType: 'danger',
      nzOnOk: () => this.dataService.deleteAuth(id).subscribe(res => {
        if (res.status === 200) {
          this.getAllData();
          this.createNotification('success', '权限管理', '删除成功！');
        } else {
          this.createNotification('error', '权限管理', '删除失败！');
        }
      }, (error) => {
        this.createNotification('error', '权限管理', '服务器boom!!!');
      }),
      nzCancelText: '取消',
      nzOnCancel: () => console.log(id)
    });
  }
  // 编辑行
  startEdit(key: string): void {
    console.log(this.editCache);
    this.editCache[key].edit = true;
  }
  // 离开
  cancelEdit(key: string): void {
    this.editCache[key].edit = false;
  }
  saveEdit(key: string): void {
    const index = this.dataSet.findIndex(item => item.key === key);
    Object.assign(this.dataSet[index], this.editCache[key].data);
    // this.dataSet[ index ] = this.editCache[ key ].data;
    this.editCache[key].edit = false;
  }
  // 更新修改值
  updateEditCache(): void {
    console.log(this.dataSet);
    this.dataSet.forEach(item => {
      if (!this.editCache[item.key]) {
        this.editCache[item.key] = {
          edit: false,
          data: { ...item }
        };
      }
    });
    console.log(this.dataSet);
  }
  // 新增行
  addRow(): void {
    this.i++;
    this.dataSet = [...this.dataSet, {
      key: `${this.i}`,
      action: ``,
      describe: '',
      defaultCheck: 'true'
    }];
    this.updateEditCache();
  }
  // 删除行
  deleteRow(i: string): void {
    const dataSet = this.dataSet.filter(d => d.key !== i);
    this.dataSet = dataSet;
  }
  // 检测id是否重复
  authIDAsyncValidator = (control: FormControl) => Observable.create((observer: Observer<ValidationErrors>) => {
    let re;
    re = /^[A-Za-z0-9]+$/; /*只能是数字或字母，不包括下划线的正则表达式*/
    if (re.test(control.value)) {
      this.dataService.checkAuthId(control.value).subscribe(res => {
        if (res.result.length === 0) {
          observer.next(null);
        } else {
          observer.next({ error: true, duplicated: true });
        }
        observer.complete();
      }, (error) => {
        this.createNotification('error', '权限管理', '服务器boom!!!');
      });
    } else {
      console.log('只能是数字或字母，不包括下划线');
      observer.next({ error: true, regular: true });
      observer.complete();
    }
  })
  // 搜索
  search(): void {
    const filterFunc = (item) => {
      return (item.name.indexOf(this.searchValue) !== -1);
    };
    const data = this.allData.filter(item => filterFunc(item));
    this.displayData = data.reverse();
  }
  // **************************
  // 获取数据
  getAllData(): void {
    this.dataService.getPermissionData().subscribe(res => {
      console.log(res);
      this.allData = res.result;
      this.displayData = [...this.allData].reverse();
      console.log(this.displayData);
    }, (error) => {
      this.createNotification('error', '权限管理', '服务器boom!!!');
    });
    // 类型初始值
    const children = [];
    this.listOfOption = children;

  }

  ngOnInit() {
    this.getAllData();
    this.validateForm = this.fb.group({
      authID: [null, [Validators.required], [this.authIDAsyncValidator]],
      authName: [null, [Validators.required]],
      authRemark: [null],
    });
    this.configForm = this.fb.group({
      configName: [null, [Validators.required]],
      configRemark: [null]
    });


  }

}
